package co.yixiang.modules.shop.rest;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import co.yixiang.aop.log.Log;
import co.yixiang.constant.ShopConstants;
import co.yixiang.exception.BadRequestException;
import co.yixiang.exception.ErrorRequestException;
import co.yixiang.modules.shop.domain.*;
import co.yixiang.modules.shop.service.*;
import co.yixiang.modules.shop.service.dto.*;
import co.yixiang.modules.shop.utils.ExcelUtil;
import co.yixiang.modules.shop.utils.IOUtil;
import co.yixiang.utils.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author hupeng
 * @date 2019-10-04
 */
@Api(tags = "商城:商品管理")
@RestController
@RequestMapping("api")
@Slf4j
public class StoreProductController {
    @Autowired
    private YxStoreProductService yxStoreProductService;
    @Autowired
    private YxSystemConfigService yxSystemConfigService;
    @Autowired
    private YxSupplierService yxSupplierService;

    @Autowired
    private YxStoreCategoryService yxStoreCategoryService;

    @Autowired
    private YxSystemStoreService yxSystemStoreService;
    @Autowired
    private YxSystemStoreService YxSystemStoreService

    ;


    @Log("查询商品")
    @ApiOperation(value = "查询商品")
    @GetMapping(value = "/yxStoreProduct")
//    @PreAuthorize("@el.check('admin','YXSTOREPRODUCT_ALL','YXSTOREPRODUCT_SELECT')")
    public ResponseEntity getYxStoreProducts(YxStoreProductQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity(yxStoreProductService.queryAll(criteria, pageable), HttpStatus.OK);
    }

    @Log("新增商品")
    @ApiOperation(value = "新增商品")
    @CacheEvict(cacheNames = ShopConstants.YSHOP_REDIS_INDEX_KEY, allEntries = true)
    @PostMapping(value = "/yxStoreProduct")
//    @PreAuthorize("@el.check('admin','YXSTOREPRODUCT_ALL','YXSTOREPRODUCT_CREATE')")
    public ResponseEntity create(@Validated @RequestBody YxStoreProduct resources) {
        //if(StrUtil.isNotEmpty("22")) throw new BadRequestException("演示环境禁止操作");
        if (ObjectUtil.isEmpty(resources.getGiveIntegral())) {
            resources.setGiveIntegral(BigDecimal.ZERO);
        }
        if (ObjectUtil.isEmpty(resources.getCost())) {
            resources.setCost(BigDecimal.ZERO);
        }
        //查询供应商
        if (StringUtils.isNotEmpty(resources.getSupplierCode())) {
            YxSupplier supplier = yxSupplierService.findByCode(resources.getSupplierCode());
            resources.setSupplierName(supplier != null ? supplier.getName() : null);
        }
        //查询门店
        if (StringUtils.isNotEmpty(resources.getStoreId())) {
            YxSystemStoreDto storeDto = YxSystemStoreService.findById(Integer.parseInt(resources.getStoreId()));
            resources.setStorePname(storeDto != null ? storeDto.getName() : null);
        }
        resources.setIsStockMall(0);
        if (resources.getStoreCategory().getId() == null) {
            throw new BadRequestException("请选择商品分类！");
        }
        return new ResponseEntity(yxStoreProductService.create(resources), HttpStatus.CREATED);
    }

    @Log("修改商品")
    @ApiOperation(value = "修改商品")
    @CacheEvict(cacheNames = ShopConstants.YSHOP_REDIS_INDEX_KEY, allEntries = true)
    @PutMapping(value = "/yxStoreProduct")
//    @PreAuthorize("@el.check('admin','YXSTOREPRODUCT_ALL','YXSTOREPRODUCT_EDIT')")
    public ResponseEntity update(@Validated @RequestBody YxStoreProduct resources) {
        //if(StrUtil.isNotEmpty("22")) throw new BadRequestException("演示环境禁止操作");
        //查询供应商
        if (StringUtils.isNotEmpty(resources.getSupplierCode())) {
            YxSupplier supplier = yxSupplierService.findByCode(resources.getSupplierCode());
            resources.setSupplierName(supplier != null ? supplier.getName() : null);
        } else {//修改时没有选择供应商，清空原有的供应商
            resources.setSupplierName(null);
        }
        //查询门店
        if (StringUtils.isNotEmpty(resources.getStoreId())) {
            YxSystemStoreDto storeDto = YxSystemStoreService.findById(Integer.parseInt(resources.getStoreId()));
            resources.setStorePname(storeDto != null ? storeDto.getName() : null);
        }
        resources.setInvestCost(resources.getPurchasePrice());
        if (resources.getStoreCategory().getId() == null) {
            throw new BadRequestException("请选择商品分类！");
        }
        yxStoreProductService.update(resources);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @Log("删除商品")
    @ApiOperation(value = "删除商品")
    @CacheEvict(cacheNames = ShopConstants.YSHOP_REDIS_INDEX_KEY, allEntries = true)
    @DeleteMapping(value = "/yxStoreProduct/{ids}")
//    @PreAuthorize("@el.check('admin','YXSTOREPRODUCT_ALL','YXSTOREPRODUCT_DELETE')")
    public ResponseEntity delete(@PathVariable Integer ids[]) {
        for (int i = 0; ids.length > i; i++) {
            yxStoreProductService.delete(ids[i]);
        }
        return new ResponseEntity(HttpStatus.OK);
    }

    @ApiOperation(value = "恢复数据")
    @CacheEvict(cacheNames = ShopConstants.YSHOP_REDIS_INDEX_KEY, allEntries = true)
    @DeleteMapping(value = "/yxStoreProduct/recovery/{id}")
//    @PreAuthorize("@el.check('admin','YXSTOREPRODUCT_ALL','YXSTOREPRODUCT_DELETE')")
    public ResponseEntity recovery(@PathVariable Integer id) {
        yxStoreProductService.recovery(id);
        return new ResponseEntity(HttpStatus.OK);
    }

    @ApiOperation(value = "商城商品库上架/下架")
    @CacheEvict(cacheNames = ShopConstants.YSHOP_REDIS_INDEX_KEY, allEntries = true)
    @PostMapping(value = "/yxStoreProduct/onsale/{id}")
    public ResponseEntity onSale(@PathVariable Integer id, @RequestBody String jsonStr) {
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        int status = Integer.valueOf(jsonObject.get("status").toString());
        yxStoreProductService.onSale(id, status);
        return new ResponseEntity(HttpStatus.OK);
    }

    @ApiOperation(value = "生成属性")
    @PostMapping(value = "/yxStoreProduct/isFormatAttr/{id}")
    public ResponseEntity isFormatAttr(@PathVariable Integer id, @RequestBody String jsonStr) {
        return new ResponseEntity(yxStoreProductService.isFormatAttr(id, jsonStr), HttpStatus.OK);
    }

    @ApiOperation(value = "设置保存属性")
    @CacheEvict(cacheNames = ShopConstants.YSHOP_REDIS_INDEX_KEY, allEntries = true)
    @PostMapping(value = "/yxStoreProduct/setAttr/{id}")
    public ResponseEntity setAttr(@PathVariable Integer id, @RequestBody String jsonStr) {
        yxStoreProductService.createProductAttr(id, jsonStr);
        return new ResponseEntity(HttpStatus.OK);
    }

    @ApiOperation(value = "清除属性")
    @CacheEvict(cacheNames = ShopConstants.YSHOP_REDIS_INDEX_KEY, allEntries = true)
    @PostMapping(value = "/yxStoreProduct/clearAttr/{id}")
    public ResponseEntity clearAttr(@PathVariable Integer id) {
        yxStoreProductService.clearProductAttr(id, true);
        return new ResponseEntity(HttpStatus.OK);
    }

    @ApiOperation(value = "获取属性")
    @GetMapping(value = "/yxStoreProduct/attr/{id}")
    public ResponseEntity attr(@PathVariable Integer id) {
        String str = yxStoreProductService.getStoreProductAttrResult(id);
        if (StrUtil.isEmpty(str)) {
            return new ResponseEntity(HttpStatus.OK);
        }
        JSONObject jsonObject = JSON.parseObject(str);

        return new ResponseEntity(jsonObject, HttpStatus.OK);
    }

    @Log("查询没有成本价的商品记录数")
    @ApiOperation("查询没有成本价的商品记录数")
    @GetMapping("/yxStoreProduct/findCostTotal")
    public ResponseEntity findCostTotal() {
        List<YxStoreProduct> list = yxStoreProductService.findAllPriceNull();
        Map<String, Object> map = new HashMap<>();
        map.put("total", 0);
        if (list != null && list.size() > 0) {
            map.put("total", list.size());
        }
        return new ResponseEntity(map, HttpStatus.OK);
    }

    @Log("导出没有成本价商品信息")
    @ApiOperation("导出没有成本价商品信息")
    @GetMapping("/yxStoreProduct/doExportCostPrice")
    public void doExportCostPrice(HttpServletResponse response) throws IOException {
        List<YxStoreProduct> list = yxStoreProductService.findAllPriceNull();
        List<Map<String, Object>> listData = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (YxStoreProduct storeProduct : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("商品ID", storeProduct.getId());
                map.put("商品名称", storeProduct.getStoreName());
                map.put("成本价", "");
                listData.add(map);
            }
            FileUtil.downloadExcel(listData, response);
        }
    }

    @Log("导入商品成本价")
    @ApiOperation("导入商品成本价")
    @PostMapping("/yxStoreProduct/doImportCost")
    public ResponseEntity doImportCost(@RequestParam("file") MultipartFile file) {
        List<List<String>> list = new ArrayList<List<String>>();
        String filaName = file.getOriginalFilename();// 获取文件名
        String prefix = filaName.substring(filaName.lastIndexOf(".") + 1);// 获取文件后缀
        Map<String, Object> map = new HashMap<>(2);
        map.put("errno", 0);
        map.put("msg", "导入失败");
        try {
            InputStream in = file.getInputStream();
            if ("xlsx".equals(prefix.toLowerCase())) {
                list = IOUtil.importXlsxByType(in);// 导入xlsx格式
            } else if ("xls".equals(prefix.toLowerCase())) {
                list = IOUtil.importXlsByType(in);// 导入xls格式
            }
            if (list != null && list.size() > 0) {
                YxSystemConfig systemConfig1 = yxSystemConfigService.findByKey("product_price_ratio1");
                YxSystemConfig systemConfig2 = yxSystemConfigService.findByKey("product_price_ratio2");
                //因子1
                Double value1 = Double.parseDouble(systemConfig1.getValue());
                //因子2
                Double value2 = Double.parseDouble(systemConfig2.getValue());
                for (List<String> li : list) {
                    if (li.get(1) != null) {
                        YxStoreProduct storeProduct = new YxStoreProduct();
                        storeProduct.setId(Integer.parseInt(li.get(1)));
                        storeProduct.setStoreName(li.get(0));
                        Double cost = Double.parseDouble(li.get(2));
                        Double newCost = (cost * (1 + value1)) * (1 + value2);
                        BigDecimal big = new BigDecimal(newCost);
                        storeProduct.setCost(big);
                        yxStoreProductService.update(storeProduct);
                    }
                }
                map.put("errno", 1);
                map.put("msg", "导入成功");
            } else {
                map.put("msg", "导入文件是空文件，请重新导入");
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("msg", "导入失败,请检查成本价格式是否有误(成本价只能是整数或小数)");
        }

        return new ResponseEntity(map, HttpStatus.NO_CONTENT);
    }

    @Log("添加商品到认购商品库")
    @ApiOperation("添加商品到认购商品库")
    @PostMapping("/yxStoreProduct/doAddInvestmentPool")
    public ResponseEntity doAddInvestmentPool(@Validated @RequestBody YxStoreProduct storeProduct) {
        try {
            storeProduct.setIsStockInvest(1);
            storeProduct.setIsInvestOn(0);
            yxStoreProductService.update(storeProduct);
        } catch (Exception e) {
            throw new ErrorRequestException("添加商品到认购商品库失败");
        }
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @Log("添加到商城商品管理库")
    @ApiOperation("添加到商城商品管理库")
    @GetMapping("/yxStoreProduct/doStoresMall/{ids}")
    public ResponseEntity doStoresMall(@PathVariable Integer ids[]) {
        for (int i = 0; ids.length > i; i++) {
            YxStoreProduct storeProduct = new YxStoreProduct();
            storeProduct.setId(ids[i]);
            storeProduct.setIsShow(1);
            storeProduct.setIsStockMall(1);
            yxStoreProductService.update(storeProduct);
        }
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @Log("根据多个ID查询商品")
    @ApiOperation("根据多个ID查询商品")
    @GetMapping("/yxStoreProduct/findArryById/{ids}")
    public ResponseEntity findArryById(@PathVariable Integer ids[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; ids.length > i; i++) {
            if (ids.length == 1) {
                sb.append(ids[i]);
                break;
            }
            sb.append(ids[i]);
            sb.append(",");
        }
        String id = sb.toString().substring(0, sb.toString().lastIndexOf(",") - 1);
        List<YxStoreProduct> list = yxStoreProductService.findArryById(id);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }


    @ApiOperation(value = "更新是否认购商品库商品")
    @PostMapping(value = "/yxStoreProduct/onSaleInvest/{id}")
    public ResponseEntity onSaleInvest(@PathVariable Integer id, @RequestBody String jsonStr) {
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        int isStockInvest = Integer.valueOf(jsonObject.get("isStockInvest").toString());
        yxStoreProductService.onSaleInvest(id, isStockInvest);
        return new ResponseEntity(HttpStatus.OK);
    }

    @Log("导入商品信息")
    @PostMapping("/yxStoreProduct/importStoreProduct")
    @ApiOperation(value = "导入商品信息")
    public ResponseEntity importStoreProduct(@RequestParam("file") MultipartFile file) {
        List<List<String>> list = new ArrayList<List<String>>();
        //收集导入失败商品集合(用于导出)
        List<Map<String, Object>> listError = new ArrayList<>();
        String filaName = file.getOriginalFilename();// 获取文件名
        String prefix = filaName.substring(filaName.lastIndexOf(".") + 1);// 获取文件后缀
        Map<String, Object> map = new HashMap<>(2);
        map.put("flag", 1);
        map.put("msg", "全部导入成功");
        try {
            InputStream in = file.getInputStream();
            if ("xlsx".equals(prefix.toLowerCase())) {
                list = IOUtil.importXlsxByType(in);// 导入xlsx格式
            } else if ("xls".equals(prefix.toLowerCase())) {
                list = IOUtil.importXlsByType(in);// 导入xls格式
            }
            if (list != null && list.size() > 0) {
                for (List<String> li : list) {
                    try {
                        //类别编码与商品名称为空不导入
                        if (StringUtils.isEmpty(li.get(1)) && StringUtils.isEmpty(li.get(2))) {
                            continue;
                        }
                        //保存商品信息======begin
                        YxStoreProduct storeProduct = new YxStoreProduct();
                        storeProduct.setVipPrice(BigDecimal.ZERO);
                        storeProduct.setOtPrice(BigDecimal.ZERO);
                        storeProduct.setPostage(BigDecimal.ZERO);
                        storeProduct.setSort(1);
                        storeProduct.setSales(0);
                        storeProduct.setIsShow(0);
                        storeProduct.setIsHot(0);
                        storeProduct.setIsBenefit(0);
                        storeProduct.setIsBest(0);
                        storeProduct.setIsNew(0);
                        storeProduct.setIsPostage(0);
                        storeProduct.setIsDel(0);
                        storeProduct.setMerUse(0);
                        storeProduct.setGiveIntegral(BigDecimal.ZERO);
                        storeProduct.setIsSeckill(0);
                        storeProduct.setIsBargain(0);
                        storeProduct.setIsGood(0);
                        storeProduct.setFicti(0);
                        storeProduct.setBrowse(0);
                        storeProduct.setIsStockInvest(0);
                        storeProduct.setSalesReference(0);
                        storeProduct.setPromotePrice(BigDecimal.ZERO);
                        storeProduct.setAddTime(OrderUtil.getSecondTimestampTwo());
                        storeProduct.setIsInvestOn(0);
                        storeProduct.setIsInvested(0);
                        storeProduct.setIsStockMall(0);
                        //门店ID
                        storeProduct.setStoreId(li.get(0));
                        //门店
                        if (StringUtils.isNotEmpty(li.get(0))) {
                            YxSystemStoreDto yxSystemStore = yxSystemStoreService.findById(Integer.parseInt(li.get(0).trim()));
                            if (yxSystemStore != null) {
                                storeProduct.setStoreId(String.valueOf(yxSystemStore.getId()));
                                storeProduct.setStorePname(yxSystemStore.getName());
                            }
                        }
                        if (StringUtils.isNotEmpty(li.get(1))) {
                            //通过类别编码查询商品分类
                            YxStoreCategory yxStoreCategory = yxStoreCategoryService.findByLevelCode(li.get(1).trim());
                            storeProduct.setStoreCategory(yxStoreCategory);
                        }
                        storeProduct.setCateCode(li.get(1).trim());
                        //商品名称
                        storeProduct.setStoreName(li.get(2).trim());
                        //查询供应商信息
                        YxSupplier supplier = yxSupplierService.findByCode(li.get(3).trim());
                        storeProduct.setSupplierCode(li.get(3).trim());
                        storeProduct.setSupplierName(supplier != null ? supplier.getName() : null);
                        //通过商品名,供应商,门店查询商品
                        if (StringUtils.isNotEmpty(li.get(0).trim()) && StringUtils.isNotEmpty(storeProduct.getSupplierCode()) && StringUtils.isNotEmpty(storeProduct.getStoreName())) {
                            YxStoreProduct product = yxStoreProductService.findByGoods(li.get(0).trim(), storeProduct.getStoreName(), storeProduct.getSupplierCode());
                            if (product != null) {
                                Map<String, Object> mapEroor = new HashMap<>();
                                mapEroor.put("listData", li);
                                mapEroor.put("errorMsg", "商品已存在");
                                listError.add(mapEroor);
                                continue;
                            }
                        }
                        if (StringUtils.isNotEmpty(li.get(0).trim()) && StringUtils.isNotEmpty(storeProduct.getStoreName())) {
                            //通过商品名,门店查询商品
                            YxStoreProduct product2 = yxStoreProductService.findByStoreGoods(li.get(0).trim(), storeProduct.getStoreName());
                            if (product2 != null) {
                                Map<String, Object> mapEroor = new HashMap<>();
                                mapEroor.put("listData", li);
                                mapEroor.put("errorMsg", "商品已存在");
                                listError.add(mapEroor);
                                continue;
                            }
                        }
                        //规则属性一
                        if (StringUtils.isNotEmpty(li.get(9)) && StringUtils.isNotEmpty(li.get(10))) {
                            //零售价小于成本价   -1:小于 0: 等于 1:大于
                            if (conDecimal(li.get(14).trim()).compareTo(conDecimal(li.get(13).trim())) == -1) {
                                Map<String, Object> mapEroor = new HashMap<>();
                                mapEroor.put("listData", li);
                                mapEroor.put("errorMsg", "零售价1低于成本价1");
                                listError.add(mapEroor);
                                continue;
                            }
                            //成本价小于进货价
                            if (conDecimal(li.get(13).trim()).compareTo(conDecimal(li.get(12).trim())) == -1) {
                                Map<String, Object> mapEroor = new HashMap<>();
                                mapEroor.put("listData", li);
                                mapEroor.put("errorMsg", "成本价1低于进货价1");
                                listError.add(mapEroor);
                                continue;
                            }

                        }
                        //规则属性二
                        if (StringUtils.isNotEmpty(li.get(17).trim()) && StringUtils.isNotEmpty(li.get(18).trim())) {
                            //零售价小于成本价   -1:小于 0: 等于 1:大于
                            if (conDecimal(li.get(22).trim()).compareTo(conDecimal(li.get(21).trim())) == -1) {
                                Map<String, Object> mapEroor = new HashMap<>();
                                mapEroor.put("listData", li);
                                mapEroor.put("errorMsg", "零售价2低于成本价2");
                                listError.add(mapEroor);
                                continue;
                            }
                            //成本价小于进货价
                            if (conDecimal(li.get(21).trim()).compareTo(conDecimal(li.get(20).trim())) == -1) {
                                Map<String, Object> mapEroor = new HashMap<>();
                                mapEroor.put("listData", li);
                                mapEroor.put("errorMsg", "成本价2低于进货价2");
                                listError.add(mapEroor);
                                continue;
                            }
                        }
                        //规则属性三
                        if (StringUtils.isNotEmpty(li.get(25).trim()) && StringUtils.isNotEmpty(li.get(26).trim())) {
                            //零售价小于成本价   -1:小于 0: 等于 1:大于
                            if (conDecimal(li.get(30).trim()).compareTo(conDecimal(li.get(29).trim())) == -1) {
                                Map<String, Object> mapEroor = new HashMap<>();
                                mapEroor.put("listData", li);
                                mapEroor.put("errorMsg", "零售价3低于成本价3");
                                listError.add(mapEroor);
                                continue;
                            }
                            //成本价小于进货价
                            if (conDecimal(li.get(29).trim()).compareTo(conDecimal(li.get(28).trim())) == -1) {
                                Map<String, Object> mapEroor = new HashMap<>();
                                mapEroor.put("listData", li);
                                mapEroor.put("errorMsg", "成本价3低于进货价3");
                                listError.add(mapEroor);
                                continue;
                            }
                        }

                        //产地
                        if (StringUtils.isNotEmpty(li.get(4))) {
                            storeProduct.setPlace(li.get(4).trim());
                            Integer dictId = yxStoreProductService.findDetailId("product_nation", li.get(4));
                            storeProduct.setPlaceId(dictId);
                        }
                        //品牌
                        if (StringUtils.isNotEmpty(li.get(5))) {
                            Integer bid = yxStoreProductService.findBrandId(li.get(5).trim());
                            storeProduct.setBrandId(bid);
                            storeProduct.setBrandName(li.get(5).trim());
                        }
                        // 单位
                        storeProduct.setUnitName(li.get(6).trim());
                        //起订量
                        storeProduct.setMiniQuantity(li.get(7).trim());
                        //备注
                        storeProduct.setRemark(li.get(8).trim());
                        //产品条码
                        storeProduct.setBarCode(li.get(11).trim());
                        //商品进货价
                        storeProduct.setCost(conDecimal(li.get(12).trim()));
                        //成本价
                        if (StringUtils.isNotEmpty(li.get(13))) {
                            if (li.get(13).contains(".")) {
                                int i = li.get(13).indexOf(".");
                                String st = li.get(13).substring(i, li.get(13).length());
                                if (st.length() >= 3) {
                                    BigDecimal big = NumberUtil.add(conDecimal(li.get(13)), 0.1);
                                    String ne = big.toString();
                                    ne = ne.substring(0, ne.indexOf(".") + 2);
                                    storeProduct.setPurchasePrice(conDecimal(ne));
                                    storeProduct.setInvestCost(conDecimal(ne));
                                } else {
                                    storeProduct.setPurchasePrice(conDecimal(li.get(13)));
                                    storeProduct.setInvestCost(conDecimal(li.get(13)));
                                }
                            } else {
                                storeProduct.setPurchasePrice(conDecimal(li.get(13)));
                                storeProduct.setInvestCost(conDecimal(li.get(13)));
                            }
                        }

                        //零售价
                        storeProduct.setPrice(conDecimal(li.get(14).trim()));
                        //库存
                        storeProduct.setStock(conInteger(li.get(15).trim()));
                        storeProduct.setSalesReference(conInteger(li.get(16).trim()));
                        YxStoreProductDTO dto = yxStoreProductService.create(storeProduct);
                        List<FromatDetailDTO> listDetailDTO = new ArrayList<>();
                        List<ProductFormatDTO> listFormatDTO = new ArrayList<>();
                        if (StringUtils.isNotEmpty(li.get(9)) && StringUtils.isNotEmpty(li.get(10))) {
                            Map<String, Object> productAttr = getProductAttr(dto.getId(), li.get(9).trim(), li.get(10).trim(), li.get(11).trim(), conDecimal(li.get(12).trim()),
                                    storeProduct.getPurchasePrice(), conDecimal(li.get(14).trim()), conInteger(li.get(15).trim()), conInteger(li.get(16).trim()));
                            listDetailDTO.addAll((List<FromatDetailDTO>) productAttr.get("listDetailDTO"));
                            listFormatDTO.addAll((List<ProductFormatDTO>) productAttr.get("listFormatDTO"));

                        }
                        if (StringUtils.isNotEmpty(li.get(17)) && StringUtils.isNotEmpty(li.get(18))) {
                            Map<String, Object> productAttr2 = getProductAttr(dto.getId(), li.get(17).trim(), li.get(18).trim(), li.get(19).trim(), conDecimal(li.get(20).trim()),
                                    conDecimal(li.get(21).trim()), conDecimal(li.get(22).trim()), conInteger(li.get(23).trim()), conInteger(li.get(24).trim()));
                            listDetailDTO.addAll((List<FromatDetailDTO>) productAttr2.get("listDetailDTO"));
                            listFormatDTO.addAll((List<ProductFormatDTO>) productAttr2.get("listFormatDTO"));
                        }
                        if (StringUtils.isNotEmpty(li.get(25)) && StringUtils.isNotEmpty(li.get(26))) {
                            Map<String, Object> productAttr3 = getProductAttr(dto.getId(), li.get(25).trim(), li.get(26).trim(), li.get(27).trim(), conDecimal(li.get(28).trim()),
                                    conDecimal(li.get(29).trim()), conDecimal(li.get(30).trim()), conInteger(li.get(31).trim()), conInteger(li.get(32).trim()));
                            listDetailDTO.addAll((List<FromatDetailDTO>) productAttr3.get("listDetailDTO"));
                            listFormatDTO.addAll((List<ProductFormatDTO>) productAttr3.get("listFormatDTO"));
                        }
                        if (listDetailDTO.size() > 0 && listFormatDTO.size() > 0) {
                            Map<String, Object> mapData = new LinkedHashMap<>();
                            mapData.put("attr", listDetailDTO);
                            mapData.put("value", listFormatDTO);
                            yxStoreProductService.setResult(mapData, dto.getId());
                        }
                    } catch (Exception e) {
                        Map<String, Object> mapEroor = new HashMap<>();
                        mapEroor.put("listData", li);
                        mapEroor.put("errorMsg", "导入异常,请联系管理员");
                        listError.add(mapEroor);
                        log.error(e.toString());
                    }
                }
            } else {
                map.put("flag", 2);
                map.put("msg", "导入文件是空文件，请重新导入");
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("flag", 0);
            map.put("msg", "读取文件异常,请检查文件数据内容或请联系管理员");
            log.error(e.toString());
        }
        if (listError != null && listError.size() > 0) {
            //把导入失败的数据写缓存中
            RedisUtil.set("listFailure"+SecurityUtils.getUserId(), listError, 60);
            map.put("flag", 3);
            map.put("msg", "导入部分商品失败");
        }

        return new ResponseEntity(map, HttpStatus.CREATED);

    }

    @Log("获取规则属性值")
    @GetMapping("/yxStoreProduct/getListProductAttrValue/{productId}")
    public ResponseEntity getListProductAttrValue(@PathVariable Integer productId) {
        List<YxStoreProductAttrValue> list = yxStoreProductService.getListProductAttrValue(productId);
        return new ResponseEntity(list, HttpStatus.OK);
    }

    @Log("添加外部商品图")
    @PostMapping("/yxStoreProduct/addExternalFigure")
    public void addExternalFigure(@RequestBody ExternalFigureDTO resources) {
        YxStoreProduct storeProduct = new YxStoreProduct();
        if (resources.getSliderImage().length > 0) {
            StringBuffer sb = new StringBuffer();
            for (String image : resources.getSliderImage()) {
                sb.append(image);
                sb.append(",");
            }
            String sliderImage = sb.substring(0, sb.length() - 1);
            storeProduct.setSliderImage(sliderImage);
        }
        if (StringUtils.isNotEmpty(resources.getImage())) {
            storeProduct.setImage(resources.getImage());
        }
        if (StringUtils.isNotEmpty(resources.getImage()) || resources.getSliderImage().length > 0) {
            storeProduct.setId(resources.getProductId());
            yxStoreProductService.update(storeProduct);
        }
    }

    @Log("下载导入商品模版")
    @GetMapping("/yxStoreProduct/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        List<Map<String, Object>> listMap = new LinkedList<>();
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("门店编号", "1");
        map.put("类别编码", "02020106");
        map.put("商品名称", "森特莲马达加美白精华面膜");
        map.put("供应商编码", "B013");
        map.put("产地", "韩国");
        map.put("品牌", "森特莲");
        map.put("单位", "盒装");
        map.put("起订量", "1000");
        map.put("备注", "");
        map.put("商品规格名字1", "净含量");
        map.put("商品规格内容1", "200ml");
        map.put("条码1", "23423423");
        map.put("进货价1", 100);
        map.put("成本价1", 110);
        map.put("零售价1", 200);
        map.put("库存1", 300);
        map.put("供应商销量参考1", "");
        map.put("商品规格名字2", "");
        map.put("商品规格内容2", "");
        map.put("条码2", "");
        map.put("进货价2", "");
        map.put("成本价2", "");
        map.put("零售价2", "");
        map.put("库存2", "");
        map.put("供应商销量参考2", "");
        map.put("商品规格名字3", "");
        map.put("商品规格内容3", "");
        map.put("条码3", "");
        map.put("进货价3", "");
        map.put("成本价3", "");
        map.put("零售价3", "");
        map.put("库存3", "");
        map.put("供应商销量参考3", "");
        listMap.add(map);
        FileUtil.downloadExcel(listMap, response);
    }

    @Log("更新表格输入框值")
    @ApiOperation(value = "更新表格输入框值")
    @PutMapping(value = "/yxStoreProduct/updateInput")
    public ResponseEntity updateInput(@Validated @RequestBody YxStoreProduct resources) {
        yxStoreProductService.update(resources);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @Log("认购价或成本价批量更新")
    @ApiOperation(value = "认购价或成本价批量更新")
    @PutMapping(value = "/yxStoreProduct/priceUpdates")
    public ResponseEntity priceUpdates(@Validated @RequestBody PriceUpdatesCriteria resources) {
        for (Integer id : resources.getIds()) {
            YxStoreProductDTO dto = yxStoreProductService.findById(id);
            YxStoreProduct yxStoreProduct = new YxStoreProduct();
            yxStoreProduct.setId(id);
            if ("1".equals(resources.getPriceType())) {// 认购价
                BigDecimal investPrice = dto.getInvestPrice();
                if ("1".equals(resources.getOperaType())) {//提升价格
                    investPrice = NumberUtil.add(investPrice, NumberUtil.mul(investPrice, chufa(resources.getAscensionPrice(), 100)));
                } else if ("2".equals(resources.getOperaType())) {//降低价格
                    investPrice = NumberUtil.sub(investPrice, NumberUtil.mul(investPrice, chufa(resources.getAscensionPrice(), 100)));
                } else if ("3".equals(resources.getOperaType())) {//改价
                    investPrice = BigDecimal.valueOf(resources.getChangePrice());
                }
                yxStoreProduct.setInvestPrice(investPrice);
                Double houseStock= Double.valueOf(investPrice.doubleValue()/dto.getInvestCost().doubleValue());
                if(String.valueOf(houseStock).indexOf(".")!=-1){
                    String a=String.valueOf(houseStock).substring(0,String.valueOf(houseStock).indexOf("."));
                    yxStoreProduct.setWarehouseStock(Integer.parseInt(a)+1);
                }else{
                    yxStoreProduct.setWarehouseStock(houseStock.intValue());
                }
            } else {//认购成本价
                BigDecimal investCost = dto.getInvestCost();
                if ("1".equals(resources.getOperaType())) {//提升价格
                    investCost = NumberUtil.add(investCost, NumberUtil.mul(investCost, chufa(resources.getAscensionPrice(), 100)));
                } else if ("2".equals(resources.getOperaType())) {//降低价格
                    investCost = NumberUtil.sub(investCost, NumberUtil.mul(investCost, chufa(resources.getAscensionPrice(), 100)));
                } else if ("3".equals(resources.getOperaType())) {//改价
                    investCost = BigDecimal.valueOf(resources.getChangePrice());
                }
                yxStoreProduct.setInvestCost(investCost);
                Double houseStock= Double.valueOf(dto.getInvestPrice().doubleValue()/investCost.doubleValue());
                if(String.valueOf(houseStock).indexOf(".")!=-1){
                    String a=String.valueOf(houseStock).substring(0,String.valueOf(houseStock).indexOf("."));
                    yxStoreProduct.setWarehouseStock(Integer.parseInt(a)+1);
                }else{
                    yxStoreProduct.setWarehouseStock(houseStock.intValue());
                }

            }
            yxStoreProductService.update(yxStoreProduct);
        }
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    //计算百分百比小数
    public BigDecimal chufa(Double a, int b) {
        BigDecimal big = new BigDecimal(a);
        BigDecimal bigd = new BigDecimal(b);

        return big.divide(bigd);
    }

    @ApiOperation(value = "认购端批量上架/下架")
    @PostMapping(value = "/yxStoreProduct/batchOnSale")
    public ResponseEntity batchOnSale(@Validated @RequestBody BatchProductCriteria resources) {
        for (Integer id : resources.getIds()) {
            YxStoreProduct yxStoreProduct = new YxStoreProduct();
            yxStoreProduct.setId(id);
            yxStoreProduct.setIsInvestOn(resources.getIsInvestOn());
            yxStoreProductService.update(yxStoreProduct);
        }
        return new ResponseEntity(HttpStatus.OK);
    }

    @ApiOperation(value = "商城端批量上架/下架")
    @PostMapping(value = "/yxStoreProduct/shoppingOnSale")
    public ResponseEntity shoppingOnSale(@Validated @RequestBody ShoppingGoodsCriteriaParams resources) {
        for (Integer id : resources.getIds()) {
            YxStoreProduct yxStoreProduct = new YxStoreProduct();
            yxStoreProduct.setId(id);
            yxStoreProduct.setIsMallOn(resources.getIsMallOn());
            yxStoreProductService.update(yxStoreProduct);
        }
        return new ResponseEntity(HttpStatus.OK);
    }

    /**
     * 数值转换
     *
     * @param digital
     * @return
     */
    public BigDecimal conDecimal(String digital) {
        BigDecimal decimal;
        if (StringUtils.isNotEmpty(digital)) {
            decimal = new BigDecimal(digital);
        } else {
            decimal = BigDecimal.ZERO;
        }
        return decimal;
    }

    public Integer conInteger(String digital) {
        Integer number;
        if (StringUtils.isNotEmpty(digital)) {
            number = Integer.parseInt(digital);
        } else {
            number = 0;
        }
        return number;
    }

    /**
     * 组装规则属性值
     *
     * @param productId  商品id
     * @param attrName   规则属性名
     * @param attrValues 规则属性内容
     * @param barCode    产品条码
     * @param pleased    进货价
     * @param cost       成本价
     * @param price      零售价
     * @param stock      库存
     * @return
     */
    public Map<String, Object> getProductAttr(Integer productId, String attrName, String attrValues, String barCode, BigDecimal pleased,
                                              BigDecimal cost, BigDecimal price, Integer stock, Integer salesReference) {
        YxStoreProductAttrValue storeProductAttrValue = new YxStoreProductAttrValue();
        YxStoreProductAttr storeProductAttr = new YxStoreProductAttr();
        storeProductAttr.setAttrName(attrName);
        storeProductAttr.setProductId(productId);
        storeProductAttr.setAttrValues(attrValues);
        //商品规则属性值对象
        storeProductAttrValue.setProductId(storeProductAttr.getProductId());
        storeProductAttrValue.setSuk(storeProductAttr.getAttrValues());
        storeProductAttrValue.setUnique(IdUtil.simpleUUID());
        storeProductAttrValue.setSales(0);
        storeProductAttrValue.setPrice(price);
        storeProductAttrValue.setCost(cost);
        storeProductAttrValue.setPleased(pleased);
        storeProductAttrValue.setStock(stock);
        storeProductAttrValue.setBarCode(barCode);
        storeProductAttrValue.setPromotePrice(BigDecimal.ZERO);
        storeProductAttrValue.setSalesReference(salesReference);
        //保存商品的属性与商品的属性值
        yxStoreProductService.saveProductAttr(storeProductAttr, storeProductAttrValue);
        //组装规则属性结果值json串参考
        //{"attr":[{"attrHidden":true,"detailValue":"","detail":["100g","200g","300g"],"value":"重量"},{"attrHidden":true,"detailValue":"","detail":["小","大"],"value":"大小"}],"value":[{"cost":0,"price":4818,"pic":"//img13.360buyimg.com/n7/jfs/t1/117737/36/5467/93502/5eb415b1Edfd06700/7c0628ce5c692129.jpg","detail":{"重量":"100g","大小":"小"},"check":false,"sales":0},{"cost":0,"price":4818,"pic":"//img13.360buyimg.com/n7/jfs/t1/117737/36/5467/93502/5eb415b1Edfd06700/7c0628ce5c692129.jpg","detail":{"重量":"100g","大小":"大"},"check":false,"sales":0},{"cost":0,"price":4818,"pic":"//img13.360buyimg.com/n7/jfs/t1/117737/36/5467/93502/5eb415b1Edfd06700/7c0628ce5c692129.jpg","detail":{"重量":"200g","大小":"小"},"check":false,"sales":0},{"cost":0,"price":4818,"pic":"//img13.360buyimg.com/n7/jfs/t1/117737/36/5467/93502/5eb415b1Edfd06700/7c0628ce5c692129.jpg","detail":{"重量":"200g","大小":"大"},"check":false,"sales":0},{"cost":0,"price":4818,"pic":"//img13.360buyimg.com/n7/jfs/t1/117737/36/5467/93502/5eb415b1Edfd06700/7c0628ce5c692129.jpg","detail":{"重量":"300g","大小":"小"},"check":false,"sales":0},{"cost":0,"price":4818,"pic":"//img13.360buyimg.com/n7/jfs/t1/117737/36/5467/93502/5eb415b1Edfd06700/7c0628ce5c692129.jpg","detail":{"重量":"300g","大小":"大"},"check":false,"sales":0}]}
        //组装规则属性结果json串
        FromatDetailDTO detailDTO = new FromatDetailDTO();
        List<FromatDetailDTO> listDetailDTO = new ArrayList<>();
        detailDTO.setAttrHidden(true);
        List<String> listd = new ArrayList<>();
        listd.add(storeProductAttr.getAttrValues());
        detailDTO.setDetail(listd);
        detailDTO.setValue(attrName);
        listDetailDTO.add(detailDTO);
        //组装规则属性值json串(页面规则属性展示)
        List<ProductFormatDTO> listFormatDTO = new ArrayList<>();
        ProductFormatDTO formatDTO = new ProductFormatDTO();
        formatDTO.setBarCode(barCode);
        formatDTO.setPleased(pleased.doubleValue());
        formatDTO.setCost(cost.doubleValue());
        formatDTO.setPrice(price.doubleValue());
        Map<String, String> detail = new LinkedHashMap<>();
        detail.put(attrName, storeProductAttr.getAttrValues());
        formatDTO.setDetail(detail);
        formatDTO.setCheck(false);
        formatDTO.setSales(stock);
        formatDTO.setSalesReference(salesReference);
        formatDTO.setPromotePrice(0.0);
        listFormatDTO.add(formatDTO);
        Map<String, Object> mapData = new LinkedHashMap<>();
        mapData.put("listDetailDTO", listDetailDTO);
        mapData.put("listFormatDTO", listFormatDTO);
        return mapData;
    }

    @Log("商品导入后反馈文件")
    @GetMapping("/yxStoreProduct/downloadFeedback")
    public void downloadFeedback(HttpServletResponse response) throws IOException {
        List<Map<String, Object>> listData = RedisUtil.get("listFailure"+SecurityUtils.getUserId());
        List<Map<String, Object>> listMap = new LinkedList<>();
        if (listData != null && listData.size() > 0) {
            for (Map<String, Object> mapData : listData) {
                List<String> li = (List<String>) mapData.get("listData");
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("门店编号", li.get(0));
                map.put("类别编码", li.get(1));
                map.put("商品名称", li.get(2));
                map.put("供应商编码", li.get(3));
                map.put("产地", li.get(4));
                map.put("品牌", li.get(5));
                map.put("单位", li.get(6));
                map.put("起订量", li.get(7));
                map.put("备注", li.get(8));
                map.put("商品规格名字1", li.get(9));
                map.put("商品规格内容1", li.get(10));
                map.put("条码1", li.get(11));
                map.put("进货价1", li.get(12));
                map.put("成本价1", li.get(13));
                map.put("零售价1", li.get(14));
                map.put("库存1", li.get(15));
                map.put("供应商销量参考1", li.get(16));
                map.put("商品规格名字2", li.get(17));
                map.put("商品规格内容2", li.get(18));
                map.put("条码2", li.get(19));
                map.put("进货价2", li.get(20));
                map.put("成本价2", li.get(21));
                map.put("零售价2", li.get(22));
                map.put("库存2", li.get(23));
                map.put("供应商销量参考2", li.get(24));
                map.put("商品规格名字3", li.get(25));
                map.put("商品规格内容3", li.get(26));
                map.put("条码3", li.get(27));
                map.put("进货价3", li.get(28));
                map.put("成本价3", li.get(29));
                map.put("零售价3", li.get(30));
                map.put("库存3", li.get(31));
                map.put("供应商销量参考3", li.get(32));
                map.put("失败备注", mapData.get("errorMsg"));
                listMap.add(map);
            }
        } else {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("备注", "全部导入成功");
            listMap.add(map);
        }


        FileUtil.downloadExcel(listMap, response);
    }

    @ApiOperation(value = "商城商品上架/下架")
    @CacheEvict(cacheNames = ShopConstants.YSHOP_REDIS_INDEX_KEY, allEntries = true)
    @PostMapping(value = "/yxStoreProduct/onMallSale/{id}")
    public ResponseEntity onMallSale(@PathVariable Integer id, @RequestBody String jsonStr) {
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        int isMallOn = Integer.valueOf(jsonObject.get("isMallOn").toString());
        yxStoreProductService.onMallSale(id, isMallOn);
        return new ResponseEntity(HttpStatus.OK);
    }

    @ApiOperation(value = "选品库批量设置热购商品")
    @PostMapping(value = "/yxStoreProduct/hotbuyOnSale")
    public ResponseEntity hotbuyOnSale(@Validated @RequestBody BatchProductCriteria resources) {
        for (Integer id : resources.getIds()) {
            YxStoreProduct yxStoreProduct = new YxStoreProduct();
            yxStoreProduct.setId(id);
            yxStoreProduct.setIsHot(resources.getIsHot());
            yxStoreProductService.update(yxStoreProduct);
        }
        return new ResponseEntity(HttpStatus.OK);
    }

    @Log("查询库存盘点")
    @ApiOperation(value = "查询库存盘点")
    @GetMapping(value = "/yxStoreProduct/getStockTaking")
    public ResponseEntity getStockTaking(StockTakingQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity(yxStoreProductService.getStockTaking(criteria, pageable), HttpStatus.OK);
    }

    @Log("导出库存盘点")
    @PostMapping("/yxStoreProduct/exportStockTaking")
    public void exportStockTaking(HttpServletResponse response, @RequestBody StockTakingQueryCriteria criteria) throws Exception {
        List<Map<String, Object>> listMap = yxStoreProductService.stockTakingList(criteria);
        if (listMap != null && listMap.size() > 0) {
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            String[] headers = {"进货时间","商品名", "规格", "单位", "进货价", "电脑库存", "货架编号", "盘点数量", "差异数量", "差异金额", "盘点人", "核对人", "抽盘人"};
            //需要合并单元格的列
//            String[] regions = {"商品名", "规格", "单位", "进货价","电脑库存","货架编号","盘点数量","差异数量","差异金额","盘点人","核对人","抽盘人"};
            String[] regions = {"商品名", "规格", "单位", "进货价", "电脑库存", "差异数量", "差异金额"};
            for (Map<String, Object> map : listMap) {
                Map<String, String> mapObj = new LinkedHashMap<>();
                mapObj.put("进货时间", map.get("addTime") != null ? OrderUtil.stampToDate(map.get("addTime").toString()) : "");
                mapObj.put("商品名", map.get("storeName").toString());
                List<YxStoreProductAttrValue> listAttrValue = yxStoreProductService.getListProductAttrValue(Integer.parseInt(map.get("id").toString()));
                String suk = listAttrValue != null && listAttrValue.size() > 0 ? listAttrValue.get(0).getSuk() : "";
                mapObj.put("规格", suk);
                mapObj.put("单位", map.get("unitName") != null ? map.get("unitName").toString() : "");
                mapObj.put("进货价", map.get("investCost") != null ? map.get("investCost").toString() : "");
                mapObj.put("电脑库存", map.get("stock") != null ? map.get("stock").toString() : "");
                mapObj.put("货架编号", map.get("shelfNum") != null ? map.get("shelfNum").toString() : "");
                mapObj.put("盘点数量", map.get("checkStock") != null ? map.get("checkStock").toString() : "");
                mapObj.put("差异数量", map.get("differeNumber") != null ? map.get("differeNumber").toString() : "");
                mapObj.put("差异金额", map.get("differeAmount") != null ? map.get("differeAmount").toString() : "");
                mapObj.put("盘点人", map.get("adder") != null ? map.get("adder").toString() : "");
                mapObj.put("核对人", map.get("checkPeople") != null ? map.get("checkPeople").toString() : "");
                mapObj.put("抽盘人", map.get("offerorSmoke") != null ? map.get("offerorSmoke").toString() : "");
                list.add(mapObj);
            }
            String data=criteria.getBeginTime()!=null?criteria.getBeginTime().substring(0,10)+"至"+criteria.getEndTime().substring(0,10):"";
            ExcelUtil.createExcel(response, headers, list, regions, data);
        } else {
            throw new BadRequestException("没有可以导出的数据");
        }

    }

    @Log("导出认购商品信息")
    @ApiOperation("导出认购商品信息")
    @GetMapping("/yxStoreProduct/exportSubscrip")
    public void exportSubscript(HttpServletResponse response,String storeName,String isInvested,String isHot) throws IOException {
        List<Map<String, Objects>> list = yxStoreProductService.findGoodsSubscript(storeName,isInvested,isHot);
        List<Map<String, Object>> listData = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (Map<String, Objects> mapData : list) {
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("序号", mapData.get("id"));
                map.put("类别编码", mapData.get("cateCode"));
                map.put("分类名称", mapData.get("cateName"));
                map.put("商品名称", mapData.get("storeName"));
                map.put("产地", mapData.get("place"));
                map.put("品牌", mapData.get("brandNname"));
                map.put("单位", mapData.get("unitName"));
                map.put("规格", mapData.get("suk"));
                map.put("起订量", mapData.get("miniQuantity"));
                map.put("进货价", mapData.get("cost"));
                map.put("成本价", mapData.get("purchasePrice"));
                map.put("零售价", mapData.get("price"));
                map.put("认购价", mapData.get("investPrice"));
                listData.add(map);
            }
            FileUtil.downloadExcel(listData, response);
        }
    }

    @Log("导入认购商品")
    @PostMapping("/yxStoreProduct/importSubscrip")
    @ApiOperation(value = "导入认购商品")
    public ResponseEntity importSubscrip(@RequestParam("file") MultipartFile file) {
        List<List<String>> list = new ArrayList<List<String>>();
        //收集导入失败商品集合(用于导出)
        List<Map<String, Object>> listError = new ArrayList<>();
        String filaName = file.getOriginalFilename();// 获取文件名
        String prefix = filaName.substring(filaName.lastIndexOf(".") + 1);// 获取文件后缀
        Map<String, Object> map = new HashMap<>(2);
        map.put("flag", 1);
        map.put("msg", "全部导入成功");
        try {
            InputStream in = file.getInputStream();
            if ("xlsx".equals(prefix.toLowerCase())) {
                list = IOUtil.importXlsxByType(in);// 导入xlsx格式
            } else if ("xls".equals(prefix.toLowerCase())) {
                list = IOUtil.importXlsByType(in);// 导入xls格式
            }
            if (list != null && list.size() > 0) {
                for (List<String> li : list) {
                    try {
                        if (StringUtils.isEmpty(li.get(0))) {
                            Map<String, Object> mapEroor = new HashMap<>();
                            mapEroor.put("listData", li);
                            mapEroor.put("errorMsg", "序号不能为空");
                            listError.add(mapEroor);
                            continue;
                        }
                        YxStoreProductDTO dto = yxStoreProductService.findById(Integer.parseInt(li.get(0).trim()));
                        if (dto == null) {
                            Map<String, Object> mapEroor = new HashMap<>();
                            mapEroor.put("listData", li);
                            mapEroor.put("errorMsg", "根据序号查询商品不存在，无法导入!");
                            listError.add(mapEroor);
                            continue;
                        }
                        if (StringUtils.isNotEmpty(li.get(9)) && StringUtils.isNotEmpty(li.get(10))) {
                            //零售价小于成本价   -1:小于 0: 等于 1:大于
                            if (conDecimal(li.get(11).trim()).compareTo(conDecimal(li.get(10).trim())) == -1) {
                                Map<String, Object> mapEroor = new HashMap<>();
                                mapEroor.put("listData", li);
                                mapEroor.put("errorMsg", "零售价低于成本价");
                                listError.add(mapEroor);
                                continue;
                            }
                            //成本价小于进货价
                            if (conDecimal(li.get(10).trim()).compareTo(conDecimal(li.get(9).trim())) == -1) {
                                Map<String, Object> mapEroor = new HashMap<>();
                                mapEroor.put("listData", li);
                                mapEroor.put("errorMsg", "成本价低于进货价");
                                listError.add(mapEroor);
                                continue;
                            }
                            //进货价
                            dto.setCost(conDecimal(li.get(9).trim()));
                            //成本价
                            if (StringUtils.isNotEmpty(li.get(10))) {
                                if (li.get(10).contains(".")) {
                                    int i = li.get(10).indexOf(".");
                                    String st = li.get(10).substring(i, li.get(10).length());
                                    if (st.length() >= 3) {
                                        BigDecimal big = NumberUtil.add(conDecimal(li.get(10)), 0.1);
                                        String ne = big.toString();
                                        ne = ne.substring(0, ne.indexOf(".") + 2);
                                        dto.setPurchasePrice(conDecimal(ne));
//                                        dto.setInvestCost(conDecimal(ne));
                                    } else {
                                        dto.setPurchasePrice(conDecimal(li.get(10)));
//                                        dto.setInvestCost(conDecimal(li.get(10)));
                                    }
                                } else {
                                    dto.setPurchasePrice(conDecimal(li.get(10)));
//                                    dto.setInvestCost(conDecimal(li.get(10)));
                                }
                            }
                            //零售价
                            dto.setPrice(conDecimal(li.get(11).trim()));
                            //认购价
                            dto.setInvestPrice(conDecimal(li.get(12).trim()));
                            //计算仓库存量
                            Integer warehouseStock =NumberUtil.div(dto.getInvestPrice(),dto.getInvestCost()).intValue();
                            if(String.valueOf(warehouseStock).indexOf(".")!=-1){
                                warehouseStock=warehouseStock+1;
                            }
                            dto.setWarehouseStock(warehouseStock);
                            yxStoreProductService.updateSubscripGoods(dto);
                        }
                    } catch (Exception e) {
                        Map<String, Object> mapEroor = new HashMap<>();
                        mapEroor.put("listData", li);
                        mapEroor.put("errorMsg", "导入异常,请联系管理员");
                        listError.add(mapEroor);
                        log.error(e.toString());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("flag", 0);
            map.put("msg", "读取文件异常,请检查文件数据内容或请联系管理员");
            log.error(e.toString());
        }
        if (listError != null && listError.size() > 0) {
            //把导入失败的数据写缓存中
            RedisUtil.set("listSubscripFailed"+SecurityUtils.getUserId(), listError, 60);
            map.put("flag", 3);
            map.put("msg", "导入部分商品失败");
        }

        return new ResponseEntity(map, HttpStatus.CREATED);

    }

    @Log("导入认购商品失败反馈")
    @ApiOperation("导入认购商品失败反馈")
    @GetMapping("/yxStoreProduct/downloadSubscripFailed")
    public void downloadSubscripFailed(HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = RedisUtil.get("listSubscripFailed"+SecurityUtils.getUserId());
        List<Map<String, Object>> listData = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (Map<String, Object> mapData : list) {
                Map<String, Object> map = new LinkedHashMap<>();
                List<String> li = (List<String>) mapData.get("listData");
                map.put("序号", li.get(0));
                map.put("类别编码", li.get(1));
                map.put("分类名称", li.get(2));
                map.put("商品名称", li.get(3));
                map.put("产地", li.get(4));
                map.put("品牌", li.get(5));
                map.put("单位", li.get(6));
                map.put("规格", li.get(7));
                map.put("起订量", li.get(8));
                map.put("进货价", li.get(9));
                map.put("成本价", li.get(10));
                map.put("零售价", li.get(11));
                map.put("认购价", li.get(12));
                map.put("失败备注", mapData.get("errorMsg"));
                listData.add(map);
            }
            FileUtil.downloadExcel(listData, response);
        }
    }
    @Log("查询可以参与促销的商品")
    @ApiOperation(value = "查询可以参与促销的商品")
    @GetMapping(value = "/yxStoreProduct/getPromoteProduct")
    public ResponseEntity getPromoteProduct(PromoteProductQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity(yxStoreProductService.getPromoteProduct(criteria, pageable), HttpStatus.OK);
    }
    @Log("查询商品表中的品牌")
    @ApiOperation(value = "查询品牌")
    @GetMapping(value = "/yxStoreProduct/getListBrandName")
    public ResponseEntity getListBrandName(){
        List<String> list=yxStoreProductService.getListBrandName();
        return new ResponseEntity(list, HttpStatus.OK);
    }
}